import type {
  VbenFormSchema as FormSchema,
  VbenFormProps,
} from '@vben/common-ui';

import type { ComponentType } from './component';

import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { isArray } from 'lodash-es';

async function initSetupVbenForm() {
  setupVbenForm<ComponentType>({
    config: {
      // ant design vue组件库默认都是 v-model:value
      baseModelPropName: 'value',

      // 一些组件是 v-model:checked 或者 v-model:fileList
      modelPropNameMap: {
        Checkbox: 'checked',
        Radio: 'checked',
        RichTextarea: 'modelValue',
        Switch: 'checked',
        Upload: 'fileList',
      },
    },
    defineRules: {
      // 输入项目必填国际化适配
      required: (value, _params, ctx) => {
        if (value === undefined || value === null || value.length === 0) {
          return $t('ui.formRules.required', [ctx.label]);
        }
        return true;
      },
      // 选择项目必填国际化适配
      selectRequired: (value, _params, ctx) => {
        if (
          [false, null, undefined].includes(value) ||
          (isArray(value) && value.length === 0)
        ) {
          return $t('ui.formRules.selectRequired', [ctx.label]);
        }
        return true;
      },
      // 手机号必填并且校验
      mobileRequired: (value: any, _params: any, ctx: any) => {
        if (value === undefined || value === null || value.length === 0) {
          return $t('ui.formRules.required', [ctx.label]);
        }
        const pattern = /^1[3-9]\d{9}$/;
        return pattern.test(value) ? true : '手机号格式不正确';
      },
      // 手机号可不填，如填写则校验
      mobile: (value: any, _params: any) => {
        if (value === undefined || value === null || value.length === 0) {
          return true;
        }
        const pattern = /^1[3-9]\d{9}$/;
        return pattern.test(value) ? true : '手机号格式不正确';
      },
      // 邮箱必填并且校验
      emailRequired: (value: any, _params: any, ctx: any) => {
        if (value === undefined || value === null || value.length === 0) {
          return $t('ui.formRules.required', [ctx.label]);
        }
        const pattern = /^[\w.%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
        return pattern.test(value) ? true : '邮箱格式不正确';
      },
      // 邮箱可不填，如填写则校验
      email: (value: any, _params: any) => {
        if (value === undefined || value === null || value.length === 0) {
          return true;
        }
        const pattern = /^[\w.%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
        return pattern.test(value) ? true : '邮箱格式不正确';
      },
    },
  });
}

const useVbenForm = useForm<ComponentType>;

export { initSetupVbenForm, useVbenForm, z };

export type VbenFormSchema = FormSchema<ComponentType>;
export type { VbenFormProps };
export type FormSchemaGetter = () => VbenFormSchema[];
